package com.ruoyi.auth.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.auth.form.LoginForm;
import com.ruoyi.auth.service.AccessTokenService;
import com.ruoyi.auth.service.SysLoginService;
import com.ruoyi.captcha.model.common.ResponseModel;
import com.ruoyi.captcha.service.CaptchaService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.feign.RemoteFactoryService;

@RestController
public class TokenController
{
    @Autowired
    private AccessTokenService tokenService;

    @Autowired
    private SysLoginService    sysLoginService;

    @Autowired
    @Lazy
    private CaptchaService     captchaService;

    @Autowired
    private RemoteFactoryService  factoryService;

    @GetMapping("authtest")
    public void authtest()
    {
    	String factory = factoryService.selectRedisFactory(ServletUtils.getRequest().getHeader("token"));
    	System.out.println("微服务调用获取工厂为：" + factory);
    }

    @PostMapping("login")
    public R login(@RequestBody LoginForm form)
    {
        // 用户登录
        SysUser user = sysLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(user));
    }

    @PostMapping("login/slide")
    public R loginSilde(@RequestBody LoginForm form)
    {
        ResponseModel response = captchaService.verification(form.getVerify());
        if (response.isSuccess())
        {
            // 用户登录
            SysUser user = sysLoginService.login(form.getUsername(), form.getPassword());
            // 获取登录token
            return R.ok(tokenService.createToken(user));
        }
        return R.error().put("repCode", response.getRepCode());
    }

    @PostMapping("logout")
    public R logout(HttpServletRequest request)
    {
        String token = request.getHeader("token");
        SysUser user = tokenService.queryByToken(token);
        if (null != user)
        {
            sysLoginService.logout(user.getLoginName());
            tokenService.expireToken(user.getUserId(),token);
        }
        return R.ok();
    }

    /*
     * 获取用户信息
     * 2020.7.23
     */
    @PostMapping("login/user")
    public R user(HttpServletRequest request)
    {
        String token = request.getHeader("token");
        SysUser user = tokenService.queryByToken(token);
        if (null != user)
        {
            String userName=user.getLoginName();
            return R.ok().put("userName",userName);
        }
        return R.error(101,"用户未登录！");
    }
}
